package com.imgpro.controller;

import com.imgpro.Constant.JwtClaimsConstant;
import com.imgpro.Properties.JwtProperties;
import com.imgpro.Result.Result;
import com.imgpro.Utils.JwtUtil;
import com.imgpro.dto.UserLoginDTO;
import com.imgpro.dto.UserSingUpDTO;
import com.imgpro.entity.User;
import com.imgpro.service.UserService;
import com.imgpro.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/index")
@Slf4j
@Api(tags = "登录功能的接口")
public class LoginController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) throws Exception {
        log.info("员工登录：{}", userLoginDTO);

        User user = userService.login(userLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getUuid());

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    @ApiOperation(value = "员工退出登录")
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }


    @PostMapping("/signup")
    @ApiOperation(value = "用户登录")
    public Result<UserLoginVO> signup(@RequestBody UserSingUpDTO userSingUpDTO) throws Exception {
        log.info("用户注册，当前用户信息为：{}", userSingUpDTO);

        User user = userService.signUp(userSingUpDTO);

        //登录成功后，生成jwt令牌
//        注册成功后也算登录
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }


}
